package com.spring.schedule_system.controller;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.schedule_system.dao.TeacherDao;
import com.spring.schedule_system.entity.Classroom;
import com.spring.schedule_system.entity.Teacher;
import com.spring.schedule_system.entity.User;
import com.spring.schedule_system.utils.JwtToken;
import com.spring.schedule_system.utils.MyUtil;
import com.spring.schedule_system.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/teacher")
@Api(value = "TeacherController", description = "教师相关api")
public class TeacherController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    private TeacherDao teacherDao;


    /**
     * 添加教师
     * @param teacher_name
     * @param teacher_category
     * @param Authorization
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("添加教师")
    @PostMapping("/web/addTeacher")
    @ResponseBody
    public ResponseEntity addTeacher(@RequestParam(required = true) String teacher_name,
                                   @RequestParam(required = false) String teacher_category,
                                   @RequestHeader String Authorization) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User user = JwtToken.unsign(token, User.class);
        //用户角色，分微信用户和老师用户，1代表微信用户，2代表老师用户,默认为微信用户
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_name", teacher_name);
        Teacher teacher = teacherDao.selectOne(queryWrapper);
        if (teacher == null){
            responseEntity = ResponseEntity.ok();
            Teacher teacher1 = new Teacher();
            teacher1.setTeacher_name(teacher_name);
            teacher1.setTeacher_category(teacher_category);
            teacherDao.insert(teacher1);
            responseEntity.putDataValue("teacher_id",teacher1.getTeacher_id());
            responseEntity.putDataValue("msg","教师注册成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","教师注册失败");
        }
        return responseEntity;
    }

    /**
     * 修改教师信息
     * @param teacher_id
     * @param teacher_name
     * @param teacher_category
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("修改教师信息")
    @PutMapping("/web/updateTeacher")
    @ResponseBody
    public ResponseEntity updateTeacher(@RequestParam(required = true) int teacher_id,
                                        @RequestParam(required = false) String teacher_name,
                                        @RequestParam(required = false) String teacher_category,
                                        @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getUser_role()!=2) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;

        } else {
            responseEntity = ResponseEntity.ok();
            Teacher teacher = teacherDao.selectById(teacher_id);
            teacher.setTeacher_name(teacher_name);
            teacher.setTeacher_category(teacher_category);
            teacherDao.updateById(teacher);
            responseEntity.putDataValue("msg", "教师修改成功");
            return responseEntity;
        }
    }

    /**
     * 根据teacher_id查询教师
     * @param teacher_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据teacher_id查询教师")
    @PutMapping("/web/selectByTeacherId")
    @ResponseBody
    public ResponseEntity selectByTeacherId(@RequestParam(required = true) Integer teacher_id,
                                            @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
            responseEntity=ResponseEntity.ok();
            Teacher teacher = teacherDao.selectById(teacher_id);
        if (teacher == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "查询的教师不存在");
            return responseEntity;
        }
            responseEntity.putDataValue("teacher",teacher);
            return responseEntity;
    }

    /**
     * 根据teacher_name查询教师
     * @param teacher_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据teacher_name查询教师")
    @PutMapping("/web/selectByTeacherName")
    @ResponseBody
    public ResponseEntity selectByTeacherName(@RequestParam(required = true) String teacher_name,
                                            @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
        responseEntity=ResponseEntity.ok();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_name", teacher_name);
        Teacher teacher = teacherDao.selectOne(queryWrapper);
        if (teacher == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "查询的教师不存在");
            return responseEntity;
        }
        responseEntity.putDataValue("teacher",teacher);
        return responseEntity;
    }

    /**
     * 根据id删除教师信息
     * @param teacher_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据id删除教师信息")
    @PutMapping("/web/deleteTeacher")
    @ResponseBody
    public ResponseEntity deleteTeacher(@RequestParam(required = true) Integer teacher_id,
                                        @RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User users=JwtToken.unsign(token,User.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }
        if (users.getUser_role()!=2){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
            Teacher teacher = teacherDao.selectById(teacher_id);
            if (teacher != null) {
                teacherDao.deleteById(teacher_id);
                responseEntity = ResponseEntity.ok();
                responseEntity.putDataValue("msg", "删除成功");
                return responseEntity;
            } else {
                responseEntity = ResponseEntity.badRequest();
                responseEntity.putDataValue("msg","该教师不存在");
                return responseEntity;
            }
    }
    /**
     * 根据teacher_name删除教师信息
     * @param teacher_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据teacher_name删除教师信息")
    @PutMapping("/web/deleteTeacherByTeacherName")
    @ResponseBody
    public ResponseEntity deleteTeacherByTeacherName(@RequestParam(required = true) String teacher_name,
                                        @RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User users=JwtToken.unsign(token,User.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }
        if (users.getUser_role()!=2){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_name", teacher_name);
        Teacher teacher = teacherDao.selectOne(queryWrapper);
        if (teacher != null) {
            QueryWrapper<Teacher> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("teacher_name", teacher_name);
            teacherDao.delete(queryWrapper);
            responseEntity = ResponseEntity.ok();
            responseEntity.putDataValue("msg", "删除成功");
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","该教师不存在");
            return responseEntity;
        }
    }


    /**
     * 教师列表
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("教师列表")
    @PostMapping("/web/teachersList")
    @ResponseBody
    public ResponseEntity teachersList(@RequestHeader String Authorization,
                                      HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        List<Teacher> list = teacherDao.selectList(wrapper);
        if (list == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg", "查询的教师不存在");
            return responseData;
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("user",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 统计教师数量
     */
    @ApiOperation("统计教师数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        int  count =teacherDao.selectCount(null);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }
    /**
     * 根据teacher_id批量删除教师
     * @param arr
     * @param Authorization
     * @return
     */
    @ApiOperation("根据teacher_id批量删除教师")
    @GetMapping("/web/deleteTeacherList")
    @ResponseBody
    public ResponseEntity deleteTeacherList(@RequestParam(required = true) int[] arr,
                                         @RequestHeader String Authorization ) throws  IOException{
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        for (int teacher_id : arr) {
            Teacher teacher = teacherDao.selectById(teacher_id);
            if (teacher != null) {
                teacherDao.deleteById(teacher_id);
            }
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("msg", "批量删除数据成功");
        return responseData;
    }

    /**
     * 根据teacher_name批量删除教师
     * @param arr
     * @param Authorization
     * @return
     */
    @ApiOperation("根据teacher_name批量删除教师")
    @GetMapping("/web/deleteTeacherListByTeacherName")
    @ResponseBody
    public ResponseEntity deleteTeacherListByTeacherName(@RequestParam(required = true) String[] arr,
                                            @RequestHeader String Authorization ) throws  IOException{
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        for (String teacher_name : arr) {
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("teacher_name", teacher_name);
            Teacher teacher = teacherDao.selectOne(queryWrapper);
            if (teacher != null) {
                QueryWrapper<Teacher> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("teacher_name", teacher_name);
                teacherDao.delete(queryWrapper1);
            }
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("msg", "批量删除数据成功");
        return responseData;
    }

    /**
     * 根据teacher_name模糊查询班级
     * @param teacher_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据teacher_name模糊查询班级")
    @PutMapping("/web/selectByLikeTeacherName")
    @ResponseBody
    public ResponseEntity selectByLikeTeacherName(@RequestParam(required = true) String teacher_name, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
        responseEntity=ResponseEntity.ok();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("teacher_name", teacher_name);
        List<Teacher> teachers = teacherDao.selectList(queryWrapper);
        if (teachers == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "查询的教师不存在");
            return responseEntity;
        }
        responseEntity.putDataValue("teachers",teachers);
        return responseEntity;
    }

    /**
     * 导出教师
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("导出教师")
    @PostMapping("/web/exportTeacher")
    @ResponseBody
    public ResponseEntity exportTeacher(HttpServletResponse response) throws IOException {
        ResponseEntity responseEntity;
        responseEntity=ResponseEntity.ok();
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("Sheet1");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("教师id");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("教师名称");
        cell.setCellStyle(style);
//        cell = row.createCell(2);
//        cell.setCellValue("教师类别");
//        cell.setCellStyle(style);

        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        List<Teacher> list = teacherDao.selectList(queryWrapper);
        for (int i = 0; i < list.size() ; i++) {
            row = sheet.createRow(i+1);
            Teacher teacher = list.get(i);
            row.createCell(0).setCellValue(teacher.getTeacher_id());
            row.createCell(1).setCellValue(teacher.getTeacher_name());
            //row.createCell(2).setCellValue(teacher.getTeacher_category());
        }
        long filename = System.currentTimeMillis();
        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
        String fileName = df.format(new Date());
        response.setContentType("application/msexcel");
        response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
        response.flushBuffer();
        wb.write(response.getOutputStream());
        responseEntity.putDataValue("msg","导出成功");
        return responseEntity;
    }

}
